package com.xteam.xnetworkdisk.exception;

import com.xteam.xnetworkdisk.constant.BizCodeEnume;
import com.xteam.xnetworkdisk.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.FileNotFoundException;
import java.util.HashMap;

// 全局异常处理器
@Slf4j
@RestControllerAdvice
public class GlobalExceptionInterceptor {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());

        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errormap = new HashMap<>();

        bindingResult.getFieldErrors().forEach((item)->{
            String defaultMessage = item.getDefaultMessage();
            String field = item.getField();
            errormap.put(field,defaultMessage);
        });

        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",errormap);

    }
    @ExceptionHandler(TypeMismatchException.class)
    public R handleTypeMismatchException(TypeMismatchException e) {
        return R.error(BizCodeEnume.INVALID_PARAM.getCode(), "请求参数类型不匹配: " + e.getMessage());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        return R.error(BizCodeEnume.INVALID_PARAM.getCode(), "请求参数类型不匹配: " + e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public R globalExceptionInterceptor(RuntimeException e) {
        if(e instanceof CommonException) {
            log.error("业务错误:{}", e.getMessage());
            return R.error(e.getMessage());
        }
        log.error("系统错误:{}",e.getMessage());
        e.printStackTrace();
        return R.error();
    }
}
